/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.icybear.gae.pechapaii;

import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import net.icybear.gae.pechapaii.service.TwitterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Twitter;
import twitter4j.TwitterException;

/**
 *
 * @author Bearice
 */
@Controller
@RequestMapping("/dm.wml")
public class DirectMessage {

    @Autowired
    private TwitterService twitterService;

    @RequestMapping(params = "action=new")
    public String reply(HttpServletRequest request, String user) {
        request.setAttribute("name", user);
        return "wml/dm_new";
    }

    @RequestMapping(params = "action=send")
    public String send(HttpServletRequest request, String text, String name) {
        try {
            Twitter twitter = twitterService.createTwitter(request);
            if (twitter == null) {
                return "wml/login";
            }
            text = URLDecoder.decode(text, "utf-8");
            name = URLDecoder.decode(name, "utf-8");
            twitter.sendDirectMessage(name, text);
            return "redirect:dm.wml?sent=true";
        } catch (Exception ex) {
            request.setAttribute("message", ex);
            return "wml/error";
        }
    }

    @RequestMapping
    public String view(HttpServletRequest request) {
        return view(request, 1, false);
    }

    @RequestMapping(params = "sent")
    public String view(HttpServletRequest request, boolean sent) {
        return view(request, 1, sent);
    }

    @RequestMapping(params = {"page", "sent"})
    public String view(HttpServletRequest request, int page, boolean sent) {
        try {
            Twitter twitter = twitterService.createTwitter(request);
            if (twitter == null) {
                return "wml/login";
            }
            ResponseList<twitter4j.DirectMessage> resp;
            if (sent) {
                resp = twitter.getSentDirectMessages(new Paging(page));
            } else {
                resp = twitter.getDirectMessages(new Paging(page));
            }
            request.setAttribute("messages", resp);
            request.setAttribute("page", page);
            request.setAttribute("sent", sent);
            request.setAttribute("rateLimitStatus", resp.getRateLimitStatus());
            return "wml/dm";
        } catch (TwitterException ex) {
            request.setAttribute("message", ex);
            return "wml/error";
        }
    }
}
